<?php
/**
 * Created by PhpStorm.
 * User: Zhoujinda
 * Date: 2016/3/12
 * Time: 15:20
 */

namespace app\index\domain;

use app\index\domain\BaseDomain;
use app\admin\api\FreightTemplateApi;
use app\shop\api\AddressApi;
use app\shop\api\ProductApi;
use app\shop\api\ShoppingCartApi;

class FreightDomain extends BaseDomain{
    protected $business_code = 'freight';

    //根据商品计算运费
    public function costSku(){
        if(IS_POST){
            $this->checkVersion($this->api_ver);
            addLog("Freight/cost", $_GET, $_POST, $this->client_id . "调用运费计算接口!");

            $pid     = $this->_post('pid','','PID缺失');
            // $psku_id = $this->_post('psku_id','','PSKU_ID缺失');
            $count   = $this->_post("count",1);
            $uid     = $this->_post('uid','','用户ID缺失');
            $address_id = $this->_post('address_id','','地址ID缺失');
            $pids     = array_unique(explode(',', $pid));
            $counts   = explode(',', $count);
            if(count($counts) != count($pids)) $this->apiReturnErr('参数不匹配');
             //1.1检查收货地址 - 计算运费准备
            // if(empty($address_id)) $this->apiReturnErr('收货地址缺失');
            // $r = apiCall(AddressApi::GET_INFO,[['id'=>$address_id]]);
            // if(!$r['status']) $this->apiReturnErr($r['info']);
            // if(empty($r['info'])) $this->apiReturnErr('收货地址错误:null');
            // $address_info = $r['info']; //地址信息
            //计算运费 - 已带收货地址检查
            $post_price = 0;
            foreach ($pids as $k=>$v) {
                $r = $this->calc([['p_id'=>$v,'count'=>intval($count)]],$address_id,$uid);
                if(!$r['status']) $this->apiReturnErr($r['info']);
                $post_price += intval($r['info']);
            }
            $this->apiReturnSuc(''.$post_price);
        }else{
            $this->apiReturnErr('只支持POST请求');
        }
    }
    /**
     * 计算运费
     */
    public function cost(){
        if(IS_POST){
            $this->checkVersion($this->api_ver);
            addLog("Freight/cost", $_GET, $_POST, $this->client_id . "调用运费计算接口!");

            $cart_ids   = $this->_post('cart_ids','','购物车ID缺失');
            $address_id = $this->_post('address_id','','地址ID缺失');
            $uid = $this->_post('uid','','用户ID缺失');

            $cart_ids   = explode(',',$cart_ids);
            $freight_price = 0;

            $result = $this->groupWithPid($cart_ids);
            $info   = $result['info'];
            foreach($info as $v){
                // trace('===before calc===');
                // trace($v);
            // foreach($cart_ids as $cart_id){
                $result = $this->calc($v,$address_id,$uid);
                // trace('===after calc===');
                // trace($result);
                if($result['status']){
                    $freight_price += $result['info'];
                }else{
                    $this->apiReturnErr($result['info']);
                }

            }
            $this->apiReturnSuc($freight_price);
        }else{
            $this->apiReturnErr('只支持POST请求');
        }

    }

    /**
     * 根据单商品 - 计算运费
     * $info : [0=>['p_id'=>1,'psku_id'=>,'count=>1],1=>['p_id'=>1,'psku_id'=>,'count'=>2]]
     * psku_id 非必须
     */
    public function calc($info = [], $address_id = 0,$uid = 0){

        //购物车方式结算
        //查询购物车信息
        $p_id         = 0;
        $weight       = 0;
        $template_id  = 0;
        $template_uid = 0;
        $count        = 0;
        // trace('===info');
        // trace($info);
        foreach($info as $val){
            $p_id = $val['p_id'];
            if($val['count'] <= 0){
                addLog('Freight/cost',$_GET,$_POST,'商品id:'.$p_id.'商品数量必须大于0',true);
                return array('status'=>false,'info'=>'商品购买数量必须大于0');
            }
            if($val['count']>0) $count += $val['count'];
        }
        // trace('---count'.$count.'---');
        $map = ['id'=>  $p_id];
        $result = apiCall(ProductApi::GET_INFO,[$map]);

        if($result['status']){
            if(!empty($result['info'])){
                //查询商品价格
                $info         = $result['info'];
                $template_id  = intval($info['template_id']);
                $weight       = $info['weight'];
                $template_uid = $info['uid'];   //运费模版主人ID
            }else{
                addLog('Freight/cost',$_GET,$_POST,'商品id:'.$p_id.'数据不存在',true);
                return array('status'=>false,'info'=>'商品id:'.$p_id.'数据不存在');
            }

            //查询运费模版
            $template_info  = [];
            $freightAddress = [];
            if($template_id != 0){
                //根据模板ID计算运费
                $map = [
                    // 'uid' => $template_uid,
                    'id'  => $template_id
                ];
                $result = apiCall(FreightTemplateApi::FIND_TEMPLATE,[$map]);
                // trace('---freighttemplate find---');
                // trace($result);
                if($result['status']){
                    if(!empty($result['info'])){
                        $template_info  = $result['info'];
                        $freightAddress = $result['info']['freightAddress'];
                    }else{
                        addLog('Freight/cost',$_GET,$_POST,'运费模版id:'.$template_id.'数据不存在',true);
                        return ['status'=>false,'info'=>'运费模版id:'.$template_id.'不存在'];
                    }
                }else{
                    return ['status'=>false,'info'=>$result['info']];
                }

                //查询收获地址信息
                $address_info = 0;
                $map = [
                    'uid' =>$uid,
                    'id'  =>$address_id
                ];
                $result = apiCall(AddressApi::GET_INFO,array($map));
                if($result['status']){
                    if(!empty($result['info'])){
                        $address_info = $result['info'];
                    }else{
                        addLog('Freight/cost',$_GET,$_POST,'收货地址id:'.$address_id.'数据不存在',true);
                        return array('status'=>false,'info'=>'收货地址id:'.$address_id.'数据不存在');
                    }
                }else{
                    return ['status'=>false,'info'=>$result['info']];
                }
                // trace('---address---');
                // trace($address_info);

                //计算运费
                $add_id = 0;
                if($address_info){
                    if(!isset($address_info['cityid'])) return ['status'=>false,'info'=>'收货地址错误:city null'];
                    if($address_info['city'] == '市辖区'|| $address_info['city'] == '县' || $address_info['city']=='0' || trim($address_info['city'])==''){
                        //使用省ID去查询
                        $add_id = $address_info['provinceid'];
                    }else{
                        $add_id = $address_info['cityid'];
                    }
                }else{
                    return ['status'=>false,'info'=>'收货地址错误:address null'];
                }
                // trace('---freightAddress---');
                // trace($freightAddress);
                //遍历运费模版
                foreach($freightAddress as $key=>$val){
                    //addressids为0是全国默认运费
                    if($val['addressids'] == 0){
                        $default_freight_key = $key;
                    }else{
                        //分割地址组数组
                        $addids = explode(',',$val['addressids']);
                        //判断用户收货地址是否在地址组中
                        if(in_array($add_id,$addids)){
                            $freight_key = $key;
                            break;
                        }
                    }
                }

                if(!isset($default_freight_key)){
                    addLog('Freight/cost',$_GET,$_POST,'运费模版id:'.$template_id.'没有全国默认运费',true);
                    return array('status'=>false,'info'=>'运费模版id:'.$template_id.'没有全国默认运费');
                }

                if(!isset($freight_key)){
                    //没有局部运费，则使用全国运费
                    $freight_info = $freightAddress[$default_freight_key];
                }else{
                    $freight_info = $freightAddress[$freight_key];
                }


                //处理运费计算根据件数重量
                $type = $template_info['type'];//1:件数；2：重量;3:体积
                $count_c        = 0;//单位
                $firstpiece     = $freight_info['firstpiece'];
                $fistmoney      = $freight_info['firstmoney'];
                $replenishpiece = $freight_info['replenishpiece'];
                $replenishmoney = $freight_info['replenishmoney'];
                $freight        = 0;//总运费
                if($type==1){
                    $count_c = $count;
                }elseif($type==2){
                    $count_c = $count * $weight;
                }

                //计算首件价格
                $freight = $freight + $fistmoney;

                //如果超过首件，计算续件价格
                if($count_c > $firstpiece){
                    if(intval($replenishpiece))
                    $freight = $freight + ceil(($count_c - $firstpiece) / $replenishpiece) * $replenishmoney;
                    else
                    $freight = $freight + ($count_c - $firstpiece) * $replenishmoney;

                }

                return array('status'=>true,'info'=>''.$freight);//返回价格

            }else{
                addLog('Freight/cost',$_GET,$_POST,'商品id:'.$p_id.'未选择运费模版',true);
                return array('status'=>false,'info'=>'商品id:'.$p_id.'未选择运费模版');
            }


        }else{
            return array('status'=>false,'info'=>$result['info']);
        }


    }
    /**
     * 购物车按商品分组
     * @param  array  $cart_ids [description]
     * @return [type]           [description]
     */
    private function groupWithPid($cart_ids = array()){
        // $map = array(
        //     'id' => array('in',$cart_ids)
        // );
        $map = '`id` in ('.implode($cart_ids,',').')';
        // trace($map);
        $result = apiCall(ShoppingCartApi::QUERY_NO_PAGING,array($map));
        // trace('===before group===');
        // trace($result['info']);
        if(!$result['status']){
            return array('status'=>false,'info'=>$result['info']);
        }
        $data = array();
        foreach($result['info'] as $val){
            if(!isset($data[$val['p_id']])) $data[$val['p_id']] = array();
            array_push($data[$val['p_id']],$val);
        }
        return array('status'=>true,'info'=>$data);
    }
}